#include "func.h"
#include "token.h"

int generateToken(const char* id,char* token){
    char* jwt;
    size_t jwt_length;

    struct l8w8jwt_encoding_params params;
    l8w8jwt_encoding_params_init(&params);

    params.alg = L8W8JWT_ALG_HS512;

    params.sub = "netDisk";
    params.iss = "bit";
    params.aud = "Daoyou";

    params.iat = 0;
    params.exp = 0x7fffffff; //永远生效

    params.secret_key = (unsigned char*)id;
    params.secret_key_length = strlen(id);

    params.out = &jwt;
    params.out_length = &jwt_length;

    int r = l8w8jwt_encode(&params);    //执行加密danhansh

    if(r == L8W8JWT_SUCCESS){
        /* printf("\n l8w8jwt example HS512 token: %s \n", r == L8W8JWT_SUCCESS ? jwt : " (encoding failure) "); */
        memcpy(token,jwt,strlen(jwt));
        l8w8jwt_free(jwt);
        return 0;
    }else{
        /* Always free the output jwt string! */
        l8w8jwt_free(jwt);
        return -1;

    }
}

int generateSalt(char* salt,int length){
    char *str = (char*)calloc(1,length);
    if(str == NULL){
        return -1;
    }
    srand(time(NULL));
    int flag;
    str[0] = '$';
    str[1] = '6';
    str[2] = '$';
    str[length-1] = '$';
    for(int i=3;i<length-1;++i){
        flag = rand()%3;
        switch(flag){
            case 0:
                str[i] = 'A'+rand()%26;
                break;
            case 1:
                str[i] = 'a'+rand()%26;
                break;
            case 2:
                str[i] = '0'+rand()%10;
                break;
            default:
                str[i] = 'x';
                break;
        }
    }
    memcpy(salt,str,length);
    free(str);
    return 0;
}
